﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LastoRevival.Service.Contracts;
using LastoRevival.Service.Contracts.Models;
using LastoRevival.Service.Implementations.Exceptions;
using LastoRevival.Service.Implementations.Data;

namespace LastoRevival.Service.Implementations
{
	public class AdminService : ServiceBase, IAdminService
	{

		private UserService userService;

		public AdminService(UserService userService)
		{
			this.userService = userService;
		}

		private void VerifyAdmin(Guid loginToken)
		{
			UpdateSession(loginToken);
			VerifyLoggedIn(loginToken);

			if (!userService.GetActiveProfile(loginToken).Details.IsAdministrator)
			{
				throw new NoAccessException();
			}
		}

		private IDataProvider DataProvider
		{
			get
			{
				return DependencyFactory.GetDataProvider();
			}
		}

		/************************/

		public int CreateForum(Guid loginToken, CreateForumModel forum)
		{
			UpdateSession(loginToken);
			VerifyAdmin(loginToken);

			return DataProvider.CreateForum(forum);
		}

		public void DeleteForum(Guid loginToken, int forumID)
		{
			UpdateSession(loginToken);
			VerifyAdmin(loginToken);

			DataProvider.DeleteForum(forumID);
		}

		public void EditForum(Guid loginToken, EditForumModel forum)
		{
			throw new NotImplementedException();
		}
		
		public ViewForumAccessModel GetForumAccessPermissions(Guid loginToken, int forumID)
		{
			UpdateSession(loginToken);
			VerifyAdmin(loginToken);

			var groups = DataProvider.GetGroupAccessToForum(forumID);
			
			// remove the admin group, it's irrelevant
			// could do it in the datalayer, but this makes sure it's consistent across db types
			groups.Remove((int)BuiltInGroups.Administrator);

			return new ViewForumAccessModel
			{
				ForumID = forumID,
				Groups = groups.Values
			};
		}

		public void UpdateForumAccessPermissions(Guid loginToken, UpdateGroupPermissionsModel access)
		{
			UpdateSession(loginToken);
			VerifyAdmin(loginToken);

			DataProvider.UpdateForumAccessForForum(access);
		}


		public EditForumModel GetForumForEdit(Guid loginToken, int forumID)
		{
			UpdateSession(loginToken);
			VerifyAdmin(loginToken);

			return DataProvider.GetForumForEditing(forumID);
		}


		public void UpdateForum(Guid loginToken, EditForumModel forum)
		{
			UpdateSession(loginToken);
			VerifyAdmin(loginToken);

			DataProvider.UpdateForum(forum);
		}
	}
}
